package com.suo.enroll.controller;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suo.enroll.entry.Score;
import com.suo.enroll.entry.User;
import com.suo.enroll.service.IEnrollService;
import com.suo.enroll.service.IScoreService;
import com.suo.enroll.utils.*;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
public class EnrollController {

    final String clientId = "ACm1VXL4KW3SCdKOOl30oDUi";
    final String clientSecret = "Iir1rUyxo1nMFQuBeGLy6xzmdyTOVcYf";

    @Resource
    private IEnrollService enrollService;
    @Resource
    private IScoreService scoreService;

    @PostMapping("/ocr")
    public ResponseEntity<String> addComment(@RequestParam("qq") String qq,
                                             @RequestParam("image") MultipartFile image) throws ClientException, JSONException {

        // 判断数据库中是否已经存在该报名号
        Score existingScore = scoreService.getOne(new QueryWrapper<Score>().eq(qq != null && !qq.equals(""), "exam_number", qq));
        if (existingScore != null) {
            // 返回已提交的成绩及排名
            return getRankResponse(existingScore.getExamNumber(), existingScore.getSubject(), existingScore.getUniversity());
            //return new ResponseEntity<>("提交失败：该准考证号已经提交过", HttpStatus.OK);

        }
        // 使用 OCR 工具从图像中提取文本
        String ocr = OCRUtils.ocr(image);
        //System.out.println("OCR output: " + ocr);  // 打印 OCR 输出，帮助检查提取的文本

        String[] words = InfoUtils.getWords(ocr);
        InfoUtils.InfoResult result = InfoUtils.extractInfo(words);

        // 初始化变量
        Integer id = null;
        String examNumber = null;
        String university = null;
        String subject = null;
        String totalScore = null;
        String englishScore = null;
        String politicalTheoryScore = null;
        String mathScore = null;
        String computerScienceScore = null;


        // 遍历 OCR 提取的文本
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            // 对 word 进行预处理：去除多余的空格
            word = word.replaceAll("\\s+", "").trim();

            // 提取准考证号
            if (word.contains("准考证号") && word.split("：").length > 1) {
                examNumber = word.split("：")[1].trim();  // 提取准考证号
            }

            // 提取报考单位
            if (word.contains("报考单位") && word.split("：").length > 1) {
                university = word.split("：")[1].trim(); // 假设报考单位后跟着：
            }

            // 提取报考专业
            if (word.contains("报考专业") && word.split("：").length > 1) {
                subject = word.split("：")[1].trim(); // 假设报考专业后跟着：
            }

            // 提取总分
            if (word.contains("分") && word.split("：").length > 1) {
                totalScore = word.split("：")[1].trim();
            }

            // 提取英语成绩
            if (word.contains("英语")) {
                englishScore = words[i + 1];
            }

            // 提取思想政治理论成绩
            if (word.contains("思想政治理论")) {
                politicalTheoryScore = words[i + 1];
            }

            // 提取数学（二）成绩
            if (word.contains("数学（二）")) {
                mathScore = words[i + 1];
            }

            // 提取计算机学科专业基础成绩
            if (word.contains("计算机学科专业基础")) {
                computerScienceScore = words[i + 1];
            }
        }

        // 输出 OCR 提取结果，检查是否成功提取所有字段
//        System.out.println("examNumber: " + examNumber);
//        System.out.println("university: " + university);
//        System.out.println("subject: " + subject);
//        System.out.println("totalScore: " + totalScore);
//        System.out.println("englishScore: " + englishScore);
//        System.out.println("politicalTheoryScore: " + politicalTheoryScore);
//        System.out.println("mathScore: " + mathScore);
//        System.out.println("computerScienceScore: " + computerScienceScore);

        // 检查获取到的准考证号是否与传入的 qq 一致
        if (examNumber != null && !examNumber.equals(qq)) {
            return new ResponseEntity<>("提交失败：准考证号与成绩单中不一致", HttpStatus.OK);
        }
        //检测报考专业
        if (subject != null && !(subject.equals("人工智能") || subject.equals("计算机技术"))) {
            return new ResponseEntity<>("提交失败：报考专业必须是人工智能或计算机技术", HttpStatus.OK);
        }


        // 检查是否成功提取所有字段，若有缺失则返回错误
        if (university == null || subject == null || totalScore == null || examNumber == null) {
            return new ResponseEntity<>("提交失败：必要字段未提取", HttpStatus.OK);
        }

        // 获取图片上传到 OSS
        String url = OSSUtils.oss(image, id);

        // 保存用户信息到数据库
        scoreService.save(new Score(id, examNumber, university, subject, totalScore,
                englishScore, politicalTheoryScore, mathScore,
                computerScienceScore, url));

        // 返回当前的排名信息
        return getRankResponse(examNumber, subject, university);
        //return new ResponseEntity<>("提交成功", HttpStatus.OK);

    }

    // 获取排名信息并返回
    private ResponseEntity<String> getRankResponse(String examNumber, String subject, String university) {
        // 根据报考专业查询该专业所有的成绩数据
        List<Score> allScores = scoreService.list(new QueryWrapper<Score>().eq("university", university).eq("subject", subject));

        // 计算总分排名
        allScores.sort((a, b) -> Integer.compare(Integer.parseInt(b.getTotalScore()), Integer.parseInt(a.getTotalScore())));  // 按总分降序排序
        int totalRank = getRankForExamNumber(allScores, examNumber);

        // 计算单科排名
        int englishRank = calculateSubjectRank(allScores, examNumber, "englishScore");
        int politicalRank = calculateSubjectRank(allScores, examNumber, "politicalTheoryScore");
        int mathRank = calculateSubjectRank(allScores, examNumber, "mathScore");
        int computerScienceRank = calculateSubjectRank(allScores, examNumber, "computerScienceScore");

        String responseMessage = "提交成功！请耐心等待管理员审核！\n" +
                "在"+subject+"专业中"+"\n"+
                "总分排名: " + totalRank + "\n" ;

        return new ResponseEntity<>(responseMessage, HttpStatus.OK);
    }

    // 获取总分排名
    private int getRankForExamNumber(List<Score> allScores, String examNumber) {
        for (int i = 0; i < allScores.size(); i++) {
            if (allScores.get(i).getExamNumber().equals(examNumber)) {
                return i + 1;  // 返回当前用户的总分排名（1-based）
            }
        }
        return -1;  // 如果没有找到对应的准考证号，返回 -1
    }

    private int calculateSubjectRank(List<Score> allScores, String examNumber, String subject) {
        // 根据科目动态获取成绩
        allScores.sort((a, b) -> {
            String scoreA = getScoreBySubject(a, subject);
            String scoreB = getScoreBySubject(b, subject);
            return Integer.compare(Integer.parseInt(scoreB), Integer.parseInt(scoreA));
        });

        // 查找该用户的排名
        for (int i = 0; i < allScores.size(); i++) {
            if (allScores.get(i).getExamNumber().equals(examNumber)) {
                return i + 1;  // 返回当前用户的单科排名（1-based）
            }
        }
        return -1;  // 如果没有找到对应的准考证号，返回 -1
    }

    // 根据科目动态获取成绩
    private String getScoreBySubject(Score score, String subject) {
        switch (subject) {
            case "englishScore":
                return score.getEnglishScore();
            case "politicalTheoryScore":
                return score.getPoliticalTheoryScore();
            case "mathScore":
                return score.getMathScore();
            case "computerScienceScore":
                return score.getComputerScienceScore();
            default:
                return "0";  // 如果没有找到对应科目，返回0
        }
    }





    @GetMapping("/users/buzhunnicaidao/wsq/suijishu/19749302")
    public ResponseEntity<Page<User>> getUsers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "50") int size,  // 每一页50条
            @RequestParam(required = false) Integer id,    // 添加 ID 查询参数
            @RequestParam(required = false) String qq,
            @RequestParam(required = false) Boolean status) {  // 添加状态查询参数

        // 创建分页和查询条件，并按创建时间倒序排序
        Page<User> pageRequest = new Page<>(page, size);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // 优先根据 ID 查询，忽略其他条件
        if (id != null) {
            queryWrapper.eq("id", id);
        } else {
            // 若没有 ID，则根据 QQ 和状态进行查询
            queryWrapper.eq(qq != null && !qq.isEmpty(), "qq", qq)
                    .eq(status != null, "isOK", status)  // 根据状态进行查询
                    .orderByDesc("create_time");  // 假设创建时间字段名为 createTime
        }

        // 获取结果
        Page<User> result = enrollService.page(pageRequest, queryWrapper);

        return ResponseEntity.ok(result);
    }



    // 更新用户认证状态
    @PostMapping("/access")
    public ResponseEntity<String> accessUser(@RequestParam Integer userId) {

        if (userId == null) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }

        User user = enrollService.getById(userId);
        if (user != null) {
            user.setOK(true);
            enrollService.updateById(user);
            return ResponseEntity.ok("认证成功");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("用户未找到");
        }
    }

    @PostMapping("/delete")
    public ResponseEntity<String> deleteUser(@RequestParam Integer userId) {

        if (userId == null) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }

        User user = enrollService.getById(userId);
        if (user != null) {
            enrollService.removeById(user);
            return ResponseEntity.ok("删除成功");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("用户未找到");
        }
    }
}
